package com.mijie.homi.ns.traffic.receptor;

import java.util.Date;

import net.sf.json.JSONObject;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.constant.TypeCode;
import com.mijie.homi.common.domain.Notify;
import com.mijie.homi.common.domain.PushMessage;
import com.mijie.homi.common.domain.user.UserExtInfo;
import com.mijie.homi.common.protocol.HomiProtocol;
import com.mijie.homi.common.util.HomiUtil;
import com.mijie.homi.ns.core.HomiServer;
import com.mijie.homi.ns.service.NotifyService;
import com.mijie.homi.ns.service.UserService;
import com.mijie.util.Helper;

@Service
public class SolicitedMessageReceptor implements Receptor{

	@Autowired
	private NotifyService notifyService;
	@Autowired
	private UserService userService;
	@Autowired
	private HomiServer homiServer;
	
	@Override
	public boolean accept(short type) {
		return type==TypeCode.MESSAGE_ROUTER_TYPE_SOLICITED;
	}
	
	@Override
	public void process(int receiver,short type,JSONObject originalPack){
		if(type>0){
			IoSession receiverSession = homiServer.getIoSessionByUserId(receiver);
			
			if(receiverSession==null){
				if(type == TypeCode.UPDATE_USER_INFO || type == TypeCode.TIMELINE_DYNAMIC)
					return;
			}
			
			boolean doPush = false;
			
			Notify notify = new Notify();
			notify.setId(Helper.genUUID());
			notify.setUserId(receiver);
			notify.setType(type);
			notify.setContent(originalPack.toString());
			notify.setCreateAt(new Date());
			if(type!=TypeCode.UPDATE_USER_INFO && type!=TypeCode.NEARBY_MOOD){
				int succ = notifyService.addNotify(notify);
				doPush = (succ==1);
			}else{
				doPush = true;
			}
			
			originalPack.accumulate("notifyId", notify.getId());
			originalPack.put("createAt", new Date().getTime());
			HomiProtocol pushProtocol = new HomiProtocol(type);
			pushProtocol.setContent(originalPack.toString());
			if(doPush){
				if(receiverSession!=null){
					HomiServer.INFO("socket push solicited message type->"+type+",content->"+originalPack.toString());
					receiverSession.write(pushProtocol);
				}else{
					HomiServer.INFO("offline push solicited message type->"+type+",content->"+originalPack.toString());
					UserExtInfo extInfo = userService.getUserExtInfoByUserId(receiver);
					if(HomiUtil.doOfflinePush(notify.getType()) && extInfo!=null && extInfo.getOs().equalsIgnoreCase("ios")){
						PushMessage pushMsg = new PushMessage();
						pushMsg.setContent(notify.getContent());
						pushMsg.setId(Helper.genUUID());
						pushMsg.setContentType(notify.getType());
						pushMsg.setReceiver(receiver);
						notifyService.addToPushQueue(pushMsg);
					}
				}
			}
		}
	}
}
